package com.example.bookappgraduation.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bookappgraduation.BookListActivity;
import com.example.bookappgraduation.R;

public class SearchFragment extends Fragment {

    private EditText editTextSearchQuery;
    private Button buttonSearch;

    public SearchFragment() { /* Required empty public constructor */ }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);

        editTextSearchQuery = view.findViewById(R.id.editTextSearchQuery);
        buttonSearch = view.findViewById(R.id.buttonSearch);

        buttonSearch.setOnClickListener(v -> performSearch());

        // 实现软键盘搜索按钮的监听
        editTextSearchQuery.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }
            return false;
        });

        return view;
    }

    private void performSearch() {
        String query = editTextSearchQuery.getText().toString().trim();
        if (TextUtils.isEmpty(query)) {
            Toast.makeText(getContext(), "请输入搜索关键词", Toast.LENGTH_SHORT).show();
            return;
        }

        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && getView() != null) {
            imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
        }

        //通过 Intent 将用户输入的**搜索关键词（search_query）**传递给了 BookListActivity
        //BookListActivity 接收到 search_query 后，会构建一个包含 &q=搜索词 的 URL 来请求 API
        Intent intent = new Intent(getActivity(), BookListActivity.class);
        intent.putExtra("search_query", query);
        startActivity(intent);
    }
}